<template>
	<view>
		<!--弹窗登录-->
		<u-popup :show="showlogin" mode="center" @close="close" @open="open" :safeAreaInsetBottom="true"
			:safeAreaInsetTop="true" :overlay='true' :closeable="true" :bgColor="`#ffffff`" :round="'10px'"
			:closeOnClickOverlay="false">
			<view class="upopupbox">
				<!-- <text class="titlebox">请先登录后享受更多乐趣</text> -->
				<button class="avatar" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image :src="avatar"></image>
				</button>
				<view class="wai">
					<view class="nickbox">
						<!-- <text>昵称:</text> -->
						<input maxlength="8" type="nickname" v-model="nickname" class="weui-input"
							@change="getUsernickname" placeholder="请输入昵称" />
					</view>
					<image src="../static/images/shaizi.png" class="shaizi" @click="shaizi()"></image>

				</view>

				<view class="tipsbox">
					<text>99%+的用户选择使用微信昵称，以便后续闲置置换沟通交流</text>
				</view>
				<view class="privacybox">
					<checkbox-group @change="checkboxChange">
						<label>
							<checkbox value="valuecb" color="#534EA1" :checked="isChecked" style="transform:scale(0.7)"
								@ch />
							我已阅读并同意
							<span class="agreeclass" @click.stop="previewagree">《用户服务及隐私协议》</span>
						</label>
					</checkbox-group>
				</view>
				<view @click="xieyi">
					<u-button class="buttonbox" type="success" text="立即登录" :disabled="!isChecked"
						:open-type="isChecked?'getPhoneNumber':''" @getphonenumber="getPhoneNumber"
						customStyle="width: 600rpx" shape="circle" color="#534EA1">
					</u-button>
				</view>

			</view>
		</u-popup>
	</view>
</template>

<script>
	var self, mapCtx, qqmapsdk;
	const COS = require('cos-wx-sdk-v5');
	
	import QQMapWX from '../utils/qqmap-wx-jssdk'

	export default {
		name: "my-login",
		props: {
			showlogin: {
				type: Boolean,
				default: false
			},
		},

		data() {
			return {
				mediaUrl: uni.$http.mediaUrl,
				avatar: '',
				sk: '',
				cz: '', //是否是新用户
				content: '',
				avataru: '',
				nickname: '',
				isChecked: false,
				location: {
					latitude: 33.002883,
					longitude: 112.491943,
					address: '中国'
				},
				openid: '',
				userInfo: uni.getStorageSync('userInfo') || null,

				login_code: '',
				phoneNumber: '',
				suijiname: ["张三", "墨尘", "李四", "王麻子", "浅颜半夏", "烟雨风飘渺", "抬头看星星", "信念", "枫羽", "幼榕", "若兮",
					"守一座空城", "尽余生", "小可爱", "可爱鬼", "赴山河惊鸿宴", "刺眼的青春", "抬头那曙光", "颜绯", "明君", "哭泣的过去", "旭姿", "回眸一笑",
					"回眸一笑",
					"落雨碎江南", "少女", "冷瞳", "顾璃笙", "旧颜", "我的心上人呢", "等一个旧人", "玉枫", "伊人醉", "芈荨", "会飞的贼", "灼华", "初阳",
					"陪你春夏秋冬", "怪咖", "顾我安稳"
				]
			};
		},
		mounted() {
			self = this
			qqmapsdk = new QQMapWX({
				key: this.wemapkey
			});
			self.getCode()

			mapCtx = wx.createMapContext('idMap')
			// this.userID = this.realSystime()
			self.getAuthorizeInfo()
			// if (uni.getStorageSync('userInfo')) {
			// 	this.avataru = this.mediaUrl + this.userInfo.avatar
			// 	this.avatar = this.userInfo.avatar
			// 	this.nickname = unescape(this.userInfo.nickname);

			// 	// console.log('my-login mounted',this.currentUser,this.avatarUrl,this.nickname)
			// }
			// else if () {
			// 	this.avataru = this.mediaUrl + this.userInfo.avatar
			// 	this.avatar = this.userInfo.avatar
			// 	this.nickname = unescape(this.userInfo.nickname);

			// 	// console.log('my-login mounted',this.currentUser,this.avatarUrl,this.nickname)
			// }else{
			// 	// console.log('my-login mounted 不存在')
			// 	this.avatar = '/media/avatar/asd.png';
			// 	this.avataru = this.mediaUrl + '/media/avatar/asd.png';
			// 	this.nickname = this.shaizi()
			// 	// console.log(this.avatar)
			// }
		},
		beforeDestroy() {
			// console.log('my-login beforeDestroy')
		},
		methods: {
			shaizi() {

				var random = Math.floor(Math.random() * (this.suijiname.length - 1));
				console.log(random)
				var arr = this.suijiname[random];
				this.nickname = arr
				console.log(arr)
				return arr
			},


			realSystime() {
				var now = new Date(); //创建Date对象
				var year = now.getFullYear(); //获取年份
				var month = now.getMonth() + 1; //获取月份
				var date = now.getDate(); //获取日期
				var day = now.getDay(); //获取星期
				var hour = now.getHours(); //获取小时
				var minu = now.getMinutes(); //获取分钟
				var sec = now.getSeconds(); //获取秒
				if (month >= 1 && month <= 9) {
					month = "0" + month;
				}
				if (date >= 0 && date <= 9) {
					date = "0" + date;
				}
				if (hour >= 0 && hour <= 9) {
					hour = "0" + hour;
				}
				if (minu >= 0 && minu <= 9) {
					minu = "0" + minu;
				}
				if (sec >= 0 && sec <= 9) {
					sec = "0" + sec;
				}
				var time = '' + year + month + date + hour + minu + sec;
				return time
			},
			// 位置授权
			getAuthorizeInfo() {
				uni.authorize({
					scope: 'scope.userLocation',
					success() { // 允许授权
						// console.log('getAuthorizeInfo')
						self.getLocationInfo();
					},
					fail() { // 拒绝授权
						self.openConfirm();
						console.log("你拒绝了授权，无法获得周边信息")
					}
				})
			},
			// 再次获取授权，当用户第一次拒绝后再次请求授权
			openConfirm() {
				uni.showModal({
					title: '请求授权当前位置',
					content: '需要获取您的地理位置，请确认授权',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting(); // 打开地图权限设置
						} else if (res.cancel) {
							uni.showToast({
								title: '您拒绝了授权，无法获得附近信息',
								icon: 'none',
								duration: 3000
							})
						}
					}
				});
			},
			// 位置授权成功后，自动获取地理位置经纬度
			getLocationInfo() {
				uni.getLocation({
					type: 'gcj02',
					success(res) {
						// 移动到当前位置
						// self.toLocation(res)
						self.location.latitude = res.latitude;
						self.location.longitude = res.longitude;
						self.getAddress();
					}
				});
			},

			//逆地址解析，坐标到坐标所在位置的文字描述的转换
			getAddress() {
				qqmapsdk.reverseGeocoder({
					location: self.location || '', //获取表单传入的位置坐标,不填默认当前位置,示例为string格式
					//get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
					success: function(res) { //成功后的回调
						self.location.address = res.result.address;
						// console.log(self.location);
						// self.addressdetail = '纬度:'+ self.location.latitude+'\n'+
						//                '经度:'+ self.location.longitude+'\n'+
						// 			'地址:'+ res.result.address
					},
					fail: function(error) {
						console.error(error);
					},
					complete: function(res) {
						// console.log(res);
					}
				})
			},
			uploadFilePromise(url) {
				console.log(url)
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: uni.$http.baseUrl + 'avatarUpload/', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'avatarfile',
						formData: {
							openid: this.openid,
						},
						success: (res) => {
							var meta = JSON.parse(res.data);
							console.log(meta)
							resolve(meta.data)
						},
						fail: (res) => {
							uni.showToast({
								title: '请重选选图片',
								icon: 'error',
								duration: 1000
							})
							this.avatar=''
						}
					});
				})
			},

			// 获取code
			getCode() {
				uni.login({
					provider: 'weixin',
					success: res => {
						console.log(res.code)
						this.login_code = res.code // 获得的code
						if (this.login_code) {
							this.laoyonghu()
						}
					}
				});



			},
			async laoyonghu() {
				// console.log(self.login_code)
				var dataPost = {
					login_code: self.login_code,
				}
				const {
					data: res
				} = await uni.$http.post('getOpenid/', dataPost)
				if (res.code == 200) {
					console.log(res)
					self.sk = res.data.sk
					self.openid = res.data.oi
					uni.setStorageSync('openid', self.openid); // openid
					self.avatar = res.data.avatar
					
					if (res.data.nickname) {
						// self.nickname = unescape(res.data.nickname)
						self.nickname = res.data.nickname
						// self.avataru = this.mediaUrl + res.data.avatar;

					} else {
						// console.log('my-login mounted 不存在')
						// this.avatar = res.data.avatar;
						// this.avataru = this.mediaUrl + '/media/avatar/asd.png';
						this.nickname = this.shaizi()
						// console.log(this.avatar)
					}
					uni.login({
						provider: 'weixin',
						success: resa => {
							console.log(resa.code)
							self.login_code = resa.code
						}
					});

					// uni.showToast({ title:res.data.phoneNumber, icon: "none", duration:1000 })
					// setTimeout(() => {  self.login() }, 1000);
					// console.log('dsss:',res);
				} else {
					console.log('error:' + res.msg);
				}
			},

			xieyi() {
				if (!this.isChecked) {
					return uni.showToast({
						icon: 'none',
						title: '请阅读并同意协议'
					})
				}
			},
			// 登陆
			async getPhoneNumber(e) {

				// this.getCode()
				if (this.nickname == '') {
					return uni.showToast({
						title: '昵称不能为空',
						icon: 'error',
						duration: 2000
					})
				}

				if (e.detail.errMsg === 'getPhoneNumber:ok') {
					// console.log("确认")
					var dataPost = {
						openid: self.openid,
						session_key: self.sk,
						iv: e.detail.iv,
						encryptedData: e.detail.encryptedData
					}
					const {
						data: res
					} = await uni.$http.post('getPhone/', dataPost)
					// console.log("拿到")

					if (res.code == 200) {
						self.phoneNumber = res.data.data.phoneNumber;
						// self.openid = res.data.openid
						// uni.showToast({ title:res.data.phoneNumber, icon: "none", duration:1000 })
						// setTimeout(() => {  self.login() }, 1000);
						// console.log('dsss:',res);

						self.login()
					} else {
						console.log('error:' + res.msg);
					}
				} else {
					console.log('用户点击了拒绝');
				}
			},

			async login() {
				uni.showLoading({
					title: '登陆中...'
				})
				var yaoqingid = uni.getStorageSync('yaoqingid')
				const userInfo = {
					// nickname: escape(this.nickname),
					avatar: this.avatar,
					nickname: this.nickname,
					location: this.location,
					yaoqingid: yaoqingid,
					login_code: this.login_code,
					phoneNumber: this.phoneNumber,
					latitude: this.location.latitude,
					longitude: this.location.longitude,
					address: this.location.address,
				}

				// console.log('userInfo---',userInfo);
				// 传入后台需要校验手机号是否和openid是同一人

				// 新人默认头像都是服务器的,如果没用me证明换了头像
				// if (this.avataru.indexOf("media") < 0) {
				// 	this.uploadFilePromise(this.avataru)
				// }

				const {
					data: res
				} = await uni.$http.post('myRegister/', userInfo)
				if (res.code == 200) {
					// console.log(res);
					uni.setStorageSync('hasLogin', true)
					// 修改个人标配资料
					uni.setStorageSync('is_active', true)


						this.userInfo = {
							nickname: this.nickname,
							avatar: this.avatar,
							username: this.phoneNumber,
							latitude: this.location.latitude,
							longitude: this.location.longitude,
							address: this.location.address,
							coins: 3,
						}
						uni.setStorageSync('userInfo', this.userInfo)
						uni.setStorageSync('userid', res.data.id)
						uni.hideLoading();
						uni.showToast({
							title: '您好，首次登陆赠送您三个金币，祝您购物愉快!',
							icon: 'none',
							duration: 1000
						})
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/home/home'
							})
						}, 1000);

				} else if (res.code == 100) {
					// console.log(this.avataru)
					uni.setStorageSync('is_active', true)

						// console.log(res)
						this.userInfo = {
							nickname: this.nickname,
							avatar: this.avatar,
							username: this.phoneNumber,
							latitude: this.location.latitude,
							longitude: this.location.longitude,
							address: this.location.address,

						}
						// console.log(this.userInfo)
						uni.setStorageSync('userInfo', this.userInfo)
						uni.setStorageSync('userid', res.data.id)

						uni.setStorageSync('hasLogin', true)
						uni.showToast({
							title: '欢迎回来，祝您购物愉快!',
							icon: 'none',
							duration: 1000
						})
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/home/home'
							})
						}, 1000);



				} else if (res.code == 201) {
					// console.log(this.avataru)
					uni.setStorageSync('is_active', false)

					// if (this.avataru.indexOf("media") < 0) {
					// 	this.avatar = this.uploadFilePromise(this.avataru)
					// }
					this.userInfo = {
						nickname: this.nickname,
						avatar: this.avatar,
						checker: res.data.checker,
						username: this.phoneNumber,
						latitude: this.location.latitude,
						longitude: this.location.longitude,
						address: this.location.address,
						userId: 0,

					}
					// console.log(this.userInfo)
					uni.setStorageSync('userInfo', this.userInfo)
					uni.setStorageSync('hasLogin', true)
					uni.showToast({
						title: '该账号已被冻结，有疑问请联系客服',
						icon: 'none',
						duration: 2000
					})
					setTimeout(() => {
						uni.reLaunch({
						url: '/pages/mine/mine'
						})
					}, 2000);
				} else {
					console.log('error：' + res.msg)
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
					uni.hideLoading();
				}

			},
			open() {
				// console.log('my-login beforeDestroy')
			},
			close() {
				this.$emit("update:showlogin", false);
				// console.log('close'+this.showlogin);
			},
			// 实际上这里需要做个次数校验,如果高频调用则直接拉黑
			async onChooseAvatar(e) {
				// const {
				// 	avatarUrl
				// } = e.detail
				// this.avataru = e.detail.avatarUrl
				// console.log(this.avataru)
				// 此时需要上传图片到cos
				
				const {
					avatarUrl: filePath
				} = e.detail
				const cos = new COS({
					SecretId: 'AKIDDKRWo9cAkIvz0ptpZFl4sjUD55xdJrW7',
					SecretKey: 'd5LRK1WotmU0JiDYhePyKfp5KPL9mJhu',
				});
				uni.getFileSystemManager().readFile({
					filePath: filePath,
					success: (res) => {
						cos.putObject({
							Bucket: 'lyg-1254016590', // 存储桶名称
							Region: 'ap-nanjing', // 区域
							Key: '/avatar/' + Date.now() + '-' + Math.random().toString(36)
								.substr(2, 8), // 文件路径及名称
							Body: res.data,
							onProgress: (progressData) => {
								console.log('进度:', JSON.stringify(progressData));
							}
						}, (err, data) => {
							if (err) {
								console.error('上传失败:', err);
							} else {
								console.log('上传成功:', data);
								this.avatar = 'https://' + data.Location
							}
						});
					},
					fail: (error) => {
						console.error('读取文件失败:', error);
					}
				});
				
			},
			getUsernickname(e) {
				// console.log('点击昵称')
				const getnickname = e.detail.value
				if (getnickname) {
					this.nickname = getnickname
					// console.log(this.nickname)
				}
			},
			inputChange(e) {
				// console.log('e---',e)
				const key = e.currentTarget.dataset.key;
				this[key] = e.detail.value;
			},
			previewagree() {
				console.log(2)
				uni.navigateTo({
					url: '/pages/mine/agreement'
				})
			},
			checkboxChange: function(e) {
				// console.log(1)
				this.isChecked = e.detail.value.length > 0
			},
		}
	}
</script>

<style lang="scss">
	.wai {
		position: relative;

	}

	.shaizi {
		position: absolute;
		top: -0px;
		right: 50px;
		width: 30px;
		height: 30px;
	}

	.upopupbox {
		width: 700rpx;
		padding-bottom: 60rpx;
		margin-top: -8px;

		.titlebox {
			font-size: 14px;
			display: flex;
			justify-content: center;
		}

		.avatar {
			margin-top: 20px;
			width: 60px;
			height: 60px;
			border-radius: 60px;
			padding: 0;
			background: none;

			image {
				width: 60px;
				height: 60px;
				border-radius: 60px;
			}
		}

		.nickbox {
			margin-top: 20rpx;
			margin-bottom: 20rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #545454;

			text {
				margin-left: -100rpx;
				margin-right: 10px;
			}

			input {
				background-color: #f8f6fc;
				width: 140px;
				padding: 4px;
				text-align: center;
			}
		}

		.tipsbox {
			background-color: #fafafa;
			color: #545454;
			width: 80%;
			margin-left: 10%;
			padding: 6px;
			font-size: 12px;
		}

		.privacybox {
			color: #545454;
			width: 80%;
			margin-left: 10%;
			padding: 6px;
			font-size: 12px;
			margin-top: 20rpx;
			margin-bottom: 20rpx;

			.agreeclass {
				color: #534EA1;
			}
		}

		.buttonbox {
			margin-bottom: 10rpx;
			background: -webkit-linear-gradIEnt(left, #6C64D0, #8481C8) !important;
		}
	}
</style>